import React from 'react';
import { message } from 'antd';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import { addUser, updateUser } from '../services/user';

export default (props) => {
  const { visible, onVisibleChange, onSuccess, record } = props;
  const edit = !!record.id;

  const onFinish = async (values) => {
    const result = edit ? await updateUser({ id: record.id, ...values }) : await addUser(values);
    if (result.success) {
      message.success('保存成功');
      onSuccess();
    } else if (result.message) {
      message.error(result.message);
    }
    return result.success;
  };

  return (
    <ModalForm
      initialValues={record}
      title="用户"
      width={500}
      visible={visible}
      onFinish={onFinish}
      onVisibleChange={onVisibleChange}
      validateTrigger="onBlur"
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 24 }}
    >
      <ProFormText
        name="name"
        label="姓名"
        rules={[
          {
            required: true,
            message: '请输入姓名',
          },
          {
            whitespace: true,
            message: '姓名不能是空白',
          },
          {
            max: 10,
            message: '姓名不得超过10个字符',
          },
        ]}
      />
      <ProFormText
        name="username"
        label="用户名"
        placeholder="登录用户名必须全局唯一"
        rules={[
          {
            required: true,
            message: '请输入用户名',
          },
          {
            max: 20,
            message: '用户名不得超过20个字符',
          },
          {
            pattern: /^[0-9a-zA-Z_]+$/,
            message: '只允许包含数字、字母、下划线',
          },
        ]}
      />
    </ModalForm>
  );
};
